# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.

import sys
import os
import logging
import logging.handlers
import smtplib
import datetime
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.interfaces import PoolListener
from sqlalchemy.exc import *
from sqlalchemy.interfaces import ConnectionProxy
from sqlalchemy.pool import NullPool
import psycopg2

class MyProxy(ConnectionProxy):

    def cursor_execute(self, execute, cursor, statement, parameters, context, executemany):
        from preEnv import session
        try:
            return execute(cursor, statement, parameters, context)
        except OperationalError as e:
            print "UN ERRORE È STATO INTERCETTATO E SEGNALATO: "+ str(e)
        except IntegrityError as e:
            print "IntegrityError UN ERRORE È STATO INTERCETTATO E SEGNALATO: "+ str(e)
            session.rollback()
        except ProgrammingError as e:
            print "UN ERRORE È STATO INTERCETTATO E SEGNALATO: "+str(e)
            session.rollback()
            delete_pickle()
        except InvalidRequestError as e:
            print "UN ERRORE È STATO INTERCETTATO E SEGNALATO: "+str(e)
            session.rollback()
        except AssertionError as e:
            print "UN ERRORE È STATO INTERCETTATO E SEGNALATO\n Possibile tentativo di cancellazione di un dato\n collegato ad altri dati fondamentali: "+str(e)
            session.rollback()
        except ValueError as e:
            print "Risulta inserito un Valore non corretto. Ricontrolla: "+str(e)
            session.rollback()

def connect():
    a=None
    try:
        from preEnv import *
        a = psycopg2.connect(user=user, host=host, port=port,
                            password=password, database=database)
        #cursor = a.cursor()
        #cursor.execute("SELECT * FROM public.ente")
        #records = cursor.fetchall()
        #st = "CI SONO  ----- {0} ------- CONNESSIONI ATTIVE AL MOMENTO".format(len(records))
        #print st
        #for r in records:
            #print r
    except Exception, e:
        a = "CONNESSIONE AL DATABASE PRO NON RIUSCITA.\n DETTAGLIO ERRORE: [%s]" % str(e)
        print a
        sys.exit()
    if a:
        return a

def psycopg2new():
    engine = create_engine('postgresql://', creator=connect,
            convert_unicode=True,
            encoding='utf-8',
            proxy=MyProxy(),
            poolclass=NullPool)
    return engine

class SetTextFactory(PoolListener):
     def connect(self, dbapi_con, con_record):
         dbapi_con.text_factory = str

def my_on_connect(dbapi_con, con_record):
    dbapi_con.text_factory = str
